package cn.android666.audiorecorder.aac

import android.text.format.DateFormat
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.channels.FileChannel

class AACSaver(sampleRateInHz: Int, channelCount: Int) {

    private val fileName = "${DateFormat.format("HHmmss", System.currentTimeMillis())}.aac"
    private val audioFile = File("/sdcard/", fileName)
    private var outputStream: FileOutputStream = FileOutputStream(audioFile)
    private var outputChannel: FileChannel = outputStream.channel

    init {
        ADTSUtil.initADTS(sampleRateInHz, channelCount) // 初始化ADTS头信息
    }

    fun close() {
        outputStream.close()
        Timber.i("录音结束，aac文件位置：${audioFile.absolutePath}")
    }

    fun write(aacByteBuffer: ByteBuffer) {
        // 1、先写ADTS头
        outputChannel.write(ADTSUtil.getADTSHeader(aacByteBuffer.remaining().toLong()))
        // 2、再写aac数据
        outputChannel.write(aacByteBuffer)
    }

}